package com.compty.paint.manager;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.compty.core.hibernate.HibernateEntityDao;
import com.compty.core.page.Page;
import com.compty.paint.domain.Bid;
import com.compty.paint.domain.BidRecord;
import com.compty.paint.domain.CustomerInfo;

/**
 * @Todo:拍卖记录
 * @CreateTime:2012-3-5 下午01:18:57
 */
public class BidRecordManager  extends HibernateEntityDao<BidRecord>{
	
	private BidManager bidManager;

	/**
	 * @param customerInfo 当前用户
	 * @param addPriceStr 加价数额
	 * @param current_price 当前报价
	 * @param bidId 拍品编号
	 * @return flag null:缺少参数或参数错误  1:竟拍成功  -1:拍品价格已更新,请重新竟拍 ;4：表示当前用户保证金不足
	 */
	public String record(CustomerInfo customerInfo, String addPriceStr,String current_price, Long bidId) {
		// TODO Auto-generated method stub
		Bid bid = bidManager.findById(bidId);
		if( bid == null){
			return null;
		}else{
			Integer bid_status = bid.getBid_status();
			Integer audit_status = bid.getAudit_status();
			if( audit_status != 2 || bid_status != 1){
//				request.setAttribute("returnMsg", "该拍品状态不正常，不能竟拍");
				return "2";
			}else{
				Date endTime  = bid.getEndTime();
				if(Calendar.getInstance().getTime().compareTo(endTime)>0 ){
//					request.setAttribute("returnMsg", "该拍品已结束竟拍，不能竟拍");
					return "3";
				}
			}
			
//			boolean bool = checkCustomerLevelForBid(bid,customerInfo);
			boolean bool = true;
			if(!bool){
//				request.setAttribute("returnMsg", "您的保证金不足，请先充值。");
				return "4";
			}
		}
		
		if( addPriceStr == null) return null;
		if( current_price == null) return null;
		
		double currentPrice = 0;
		if( bid.getCurrentBidRecord() != null){
			currentPrice = bid.getCurrentBidRecord().getBidPrice();//当前价格
		}else{
			currentPrice = bid.getBeginPrice();
		}
		
		if(!current_price.equals(String.valueOf(currentPrice))){
			return "-1";
		}
		
		Double addPrice = Double.valueOf(addPriceStr);
		double new_price = addPrice + currentPrice;
		
		BidRecord bidRecord = new BidRecord();
		bidRecord.setBid(bid);
		bidRecord.setBidPrice(new_price);
		bidRecord.setBidTime(Calendar.getInstance().getTime());
		bidRecord.setCustomerInfo(customerInfo);
		super.save(bidRecord);
		
		bid.setBidCount(bid.getBidCount()+1);
		bid.setCurrent_bidrecord_id(bidRecord.getId());
		bid.setCurrentBidRecord(bidRecord);
		bidManager.save(bid);
		
		return "1";
	}
	
	/**
	 * 检查用户是否有资格对此拍品加价
	 */
	private boolean checkCustomerLevelForBid(Bid bid,CustomerInfo customerInfo) {
		// TODO Auto-generated method stub
		String  remark = customerInfo.getRemark();
		if("super".equals(remark)){
			return true;
		}
		
		Double advance = customerInfo.getAdvance();
		BidRecord bidRecord = bid.getCurrentBidRecord();
		double beginPrice = 0;
		if( bidRecord != null){
			beginPrice = bidRecord.getBidPrice();
		}else{
			beginPrice = bid.getBeginPrice();
		}
		double limit_money = 0;
		if(beginPrice <= 500){
			limit_money = 0;
		}
		else if(beginPrice<=2500){
			limit_money = 500;
		}
		else if(beginPrice<=2500){
			limit_money = 500;
		}
		else if(beginPrice<=5000){
			limit_money = 1000;
		}
		else if(beginPrice<=10000){
			limit_money = 2000;
		}
		else if(beginPrice<=25000){
			limit_money = 5000;
		}
		
		if( advance != null && advance >= limit_money){
			return true;
		}else{
			return false;
		}
	}

	public void setBidManager(BidManager bidManager) {
		this.bidManager = bidManager;
	}

	/**
	 *@Todo:根据拍品ID 删除拍卖记录
	 *@CreateTime:2012-3-14 上午11:05:49
	 * @param id 拍品ID
	 */
	public void deleteByBidId(Serializable id) {
		// TODO Auto-generated method stub
		Session session = getSession();
		
		String hql = "delete BidRecord br where br.bid.id = ?";
		
		Query query = session.createQuery(hql);
		query.setParameter(0, id);
		
		query.executeUpdate();
	}

	/**
	 * 查询拍卖记录(去重，只显示最后一次)
	 * @param curPage
	 * @param pageSize 
	 * @param customerInfo 客户
	 * @return 分页查询结果
	 */
	@SuppressWarnings("unchecked")
	public Page queryUniqueBidRecord(final Integer curPage, final Integer pageSize, final CustomerInfo customerInfo) {
		// TODO Auto-generated method stub
		   List list  =  (List)this.getHibernateTemplate().execute(new HibernateCallback() {
		   public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				String sql = "select max(id) as mid from t_bid_record  where customer_id = ? group by bid_id order by id desc ";
				
				SQLQuery query = session.createSQLQuery(sql);
				query.setParameter(0, customerInfo.getId());
				query.setFirstResult((curPage-1)*pageSize);
				query.setMaxResults(pageSize);
				
				List list = query.addScalar("mid", Hibernate.LONG).list();
				
				return list;
			}
		});
		
		List<BidRecord> result = new ArrayList<BidRecord>();
		
		for (int i = 0; i < list.size(); i++) {
			Long id =  (Long)  list.get(i);
			BidRecord bidRecord = get(id);
			result.add(bidRecord);
		}
		Page page = new Page();
		page.setResult(result);
		page.setPageNo(curPage);
		page.setPageSize(pageSize);
		
		return page;
	}
}
